package com.xuzong.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xuzong.pojo.TbArea;
import com.xuzong.service.TbAreaService;
import com.xuzong.mapper.TbAreaMapper;
import com.xuzong.util.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
* @author lenovo
* @description 针对表【tb_area】的数据库操作Service实现
* @createDate 2024-08-02 22:06:26
*/
@Service
public class TbAreaServiceImpl extends ServiceImpl<TbAreaMapper, TbArea>
    implements TbAreaService{

    @Autowired
    TbAreaMapper tbAreaMapper;
    @Override
    public R areaList() {
        List<TbArea> list = tbAreaMapper.selectList(null);
        List<TbArea> listOne = buildTree(0, list); // 调用修改后的递归函数
        return R.ok(listOne);
    }

    private List<TbArea> buildTree(int parentId, List<TbArea> list) {
        List<TbArea> children = new ArrayList<>();

        for (TbArea area : list) {
            if (area.getParentId() == parentId) {
                List<TbArea> subChildren = buildTree(area.getAreaId(), list);
                if (!subChildren.isEmpty()) {
                    area.setChildren(subChildren);
                } else {
                    area.setChildren(null); // 将最后一级的 children 设置为 null
                }
                children.add(area);
            }
        }

        return children;
    }
}




